//
//  VKStudyDaCardController.m
//  V-Learn
//
//  Created by liubo on 2019/2/13.
//  Copyright © 2019 yxk. All rights reserved.
//

#import "VKStudyDaCardController.h"
#import <AssetsLibrary/AssetsLibrary.h>
#import <MobileCoreServices/MobileCoreServices.h>
#import <MediaPlayer/MediaPlayer.h>
#import "HXCPrepareLessonsViewController.h"
#import "UnitPicker.h"
#import "LevelPicker.h"
#import "Section2TableViewCell.h"
#import "Section3TableViewCell.h"
#import "UploadManager.h"
#import "WKLevelModel.h"

@interface VKStudyDaCardController ()<UITableViewDelegate,UITableViewDataSource,UINavigationControllerDelegate,UIImagePickerControllerDelegate,Section3TableViewCellDelegate,BasePickerViewDelegate>
@property (nonatomic,strong)UITableView * tableView;
@property (nonatomic,strong)NSMutableArray * rowMuarray;
@property (nonatomic,assign)NSInteger seleceIndexRow;

@property (nonatomic,assign) NSInteger selectedIndex;

@property (nonatomic,strong) UIButton *submitBtn;
@property (nonatomic,strong) UIButton *optionBtn;

@property (nonatomic,strong) UnitPicker *aUnitPicker;
@property (nonatomic,strong) LevelPicker *aLevelPicker;
@property (nonatomic,strong) NSMutableDictionary *data;
@property (nonatomic,strong) UploadManager *aManager;
@property (nonatomic,strong) NSString *courseId;
@property (nonatomic,strong) NSString *hourId;
@property (nonatomic,assign) BOOL isVideo;//
@property (nonatomic,assign) BOOL isImage;//
@property (nonatomic,strong) NSArray *levelArr;
@property (nonatomic,strong) NSArray *unitArr;
@property (nonatomic,strong) NSArray *dataArray;

@property (nonatomic,strong) NSMutableDictionary *unitData;

@property (nonatomic,strong) NSMutableArray *filePathArry;//链接数组
@property (nonatomic,strong) NSMutableArray *contentArray;//内容数组
@property (nonatomic,strong) NSString *fileStorePath;
@property (nonatomic,assign) BOOL addToSociety;//是否发布到朋友圈

@property (nonatomic,assign) BOOL isShowAdd;
@property (nonatomic, strong) UIImagePickerController *picker;
@property (nonatomic, assign) BOOL isbeike;

@end

@implementation VKStudyDaCardController
- (NSMutableArray *)filePathArry{
    if (!_filePathArry) {
        _filePathArry = [NSMutableArray array];
    }
    return _filePathArry;
}
- (NSMutableArray *)contentArray{
    if (!_contentArray) {
        _contentArray = [NSMutableArray array];
    }
    return _contentArray;
}
- (void)viewDidLoad {
    [super viewDidLoad];
    [self setupUI];
    [self loadLevelData];
}
- (void)setupUI{
    self.navigationItem.title = @"打卡";
    self.rowMuarray = [NSMutableArray array];
    self.data = [NSMutableDictionary dictionary];
    self.unitData = [NSMutableDictionary dictionary];
    NSMutableDictionary *aDic = [NSMutableDictionary dictionary];
    [self.rowMuarray addObject:aDic];
    CGFloat Y = [UIApplication sharedApplication].statusBarFrame.size.height + 44;
    self.tableView = [[UITableView alloc] initWithFrame:CGRectMake(0, Y, ScreenW, ScreenH - Y) style:UITableViewStyleGrouped];
    self.tableView.showsVerticalScrollIndicator = NO;
    self.tableView.showsHorizontalScrollIndicator = NO;
    self.tableView.delegate = self;
    self.tableView.dataSource = self;
    self.tableView.estimatedRowHeight = 0;
    self.tableView.estimatedSectionHeaderHeight = 0;
    self.tableView.estimatedSectionFooterHeight = 0;
    self.tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    self.tableView.separatorColor = [UIColor clearColor];
    if (@available(iOS 11.0, *)) {
        self.tableView.contentInsetAdjustmentBehavior = UIScrollViewContentInsetAdjustmentNever;
    }
    
    [self.tableView registerNib:[UINib nibWithNibName:@"Section2TableViewCell" bundle:[NSBundle mainBundle]] forCellReuseIdentifier:@"Section2TableViewCell"];
    [self.tableView registerNib:[UINib nibWithNibName:@"Section3TableViewCell" bundle:[NSBundle mainBundle]] forCellReuseIdentifier:@"Section3TableViewCell"];
    self.tableView.tableFooterView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 10, 48+22+24+4)];
    [self.view addSubview:self.tableView];
    UIView *footer = [UIView new];
    footer.frame = CGRectMake(0, 0, ScreenW, 150);
    //    [self.view addSubview:self.submitBtn];
    self.tableView.tableFooterView = footer;
    [footer addSubview:self.submitBtn];
    [footer addSubview:self.optionBtn];
    self.aManager = [UploadManager shareUploadManager];
    self.addToSociety = YES;
    
    self.isShowAdd = NO;
}
-(UIButton *)optionBtn {
    if (!_optionBtn) {
        UIButton *btn = [UIButton buttonWithType:UIButtonTypeCustom];
        btn.selected = YES;
        btn.frame = CGRectMake(15, 150-25-48-10-24, 95, 24);//ScreenH - 48 - 22 - 24 - 4
        [btn setImage:[UIImage imageNamed:@"vkstudyo"] forState:UIControlStateNormal];
        [btn setImage:[UIImage imageNamed:@"vkstudySelection"] forState:UIControlStateSelected];
        [btn setTitle:@"发布到社圈" forState:UIControlStateNormal];
        btn.titleLabel.font = [UIFont systemFontOfSize:11];
        [btn setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
        [btn addTarget:self action:@selector(optionAction:) forControlEvents:UIControlEventTouchUpInside];
        [btn setImageEdgeInsets:UIEdgeInsetsMake(0, 0, 0, 0)];
        [btn setTitleEdgeInsets:UIEdgeInsetsMake(0, 5, 0, 0)];
        _optionBtn = btn;
    }
    return _optionBtn;
}
-(UIButton *)submitBtn {
    if (!_submitBtn) {
        _submitBtn = [UIButton buttonWithType:UIButtonTypeCustom];
        _submitBtn.frame = CGRectMake(15,150-25-48, ScreenW - 15*2, 48);//ScreenH - 48 - 22
        [_submitBtn setBackgroundImage:[[UIImage imageNamed:@"vkbutton-orange"] stretchableImageWithLeftCapWidth:80 topCapHeight:24] forState:UIControlStateNormal];
        [_submitBtn setTitle:@"提 交" forState:UIControlStateNormal];
        [_submitBtn setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
        [_submitBtn addTarget:self action:@selector(submitAction) forControlEvents:UIControlEventTouchUpInside];
    }
    
    return _submitBtn;
}
-(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return 3;
}
-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    if (section == 0) {
        return 1;
    }else if (section == 1) {
        return 2;
    }else {
        return self.rowMuarray.count;
    }
}

-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    NSInteger row = indexPath.row, section = indexPath.section;
    if (section == 0) {
        UITableViewCell *cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"123"];
        cell.selectionStyle = UITableViewCellSelectionStyleNone;
        UILabel *titleLbl = [[UILabel alloc] initWithFrame:CGRectMake(16, 12, ScreenW - 16 * 2, 69 - 12)];
        titleLbl.numberOfLines = 0;
        titleLbl.font = [UIFont systemFontOfSize:10];
        
        NSString *contentStr = @"打卡规则: 查询用户上一次选择的课程和课时,（级别是指课程，课程是指单元）包含课程列表 ，此接口如果是第一次进入页面，只能先点击级别才有数据，如果先点击单元是没有数据的";
        NSMutableAttributedString *attrStr = [[NSMutableAttributedString alloc]initWithString:contentStr];
        //设置：在0-3个单位长度内的内容显示成红色
        [attrStr addAttribute:NSForegroundColorAttributeName value:[UIColor redColor] range:NSMakeRange(0, 5)];
        [attrStr addAttribute:NSFontAttributeName value:[UIFont systemFontOfSize:15] range:NSMakeRange(0, attrStr.length)];
        
        titleLbl.attributedText = attrStr;
        
        
        [cell.contentView addSubview:titleLbl];
        return cell;
    }else if (section == 1) {
        Section2TableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"Section2TableViewCell" forIndexPath:indexPath];
        cell.selectionStyle = UITableViewCellSelectionStyleNone;
        if (row == 0) {
            cell.titleLbl.text = @"级别";
            cell.contentLbl.text = self.data[@"level"][@"courseName"];
            self.courseId = self.data[@"level"][@"courseId"];
            cell.contentLbl.textColor = rgb(102,102,102);
        }else {
            cell.titleLbl.text = @"单元";
            if (self.data[@"unit"]) {
                cell.contentLbl.text = self.data[@"unit"][@"hourName"];
                self.hourId = self.data[@"unit"][@"hourId"];
                
            }else {
                cell.contentLbl.text = @"";
            }
            

            cell.contentLbl.textColor = rgb(102,102,102);
        }
//        NSLog(@"courseId=%@hourId=%@",self.courseId,self.hourId);
        return cell;
    }else {
        //添加图片的cell
        Section3TableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"Section3TableViewCell" forIndexPath:indexPath];
        cell.delegate = self;
        cell.selectionStyle = UITableViewCellSelectionStyleNone;
        cell.progressView.hidden = YES;
        NSString *text = cell.textView.text;
        //        NSLog(@"")
        
        
        
        if (self.isVideo) {
            cell.addButton.hidden = YES;
            
        }else {
            cell.addButton.hidden = NO;
        }
        if (indexPath.row==0) {
            cell.delButton.hidden = YES;
            
        }else{
            cell.delButton.hidden = NO;
        }
        if (self.rowMuarray[row][@"image"]) {
//            NSLog(@"%@",cell.textView.text);
            cell.myImageView.image = self.rowMuarray[row][@"image"];
            
            //            if (indexPath.row==0) {
            //                cell.cleanBtn.hidden = YES;
            //            }else{
            //                cell.cleanBtn.hidden = NO;
            //            }
            cell.cleanBtn.hidden = NO;
            if ([self.rowMuarray[row][@"fileType"] isEqualToString:@"1"]) {
                cell.progressView.hidden = NO;
            }
        }else {
            cell.myImageView.image = [UIImage imageNamed:@"vkadd"];
            cell.cleanBtn.hidden = YES;
        }
        if (self.isShowAdd) {
            cell.addButton.hidden = NO;
        }else{
            cell.addButton.hidden = YES;
        }
        
        return cell;
    }
}

-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    NSInteger row = indexPath.row, section = indexPath.section;
    if (section == 0) {
        return 69.0;
    }else if (section == 1) {
        return 44.0;
    }else {
        return 270.0;
    }
}

-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
//    NSLog(@"tableView %zd",indexPath.row);
    NSInteger row = indexPath.row, section = indexPath.section;
    __weak typeof(self) weakSelf = self;
    if (section == 1) {
        if (row == 0) {
            
            [self.aLevelPicker loadDataWith:^{
                if (weakSelf.aLevelPicker.arrData.count <= 0) {
                    
                    [MBProgressHUD showSuccess:@"当前没有可打卡课时" toView:self.view];
                    return;
                }
                [weakSelf.aLevelPicker show];
            }];

        }else {
            if (self.data[@"level"]) {
                
                self.aUnitPicker.courseId = [self.data[@"level"][@"courseId"] integerValue];
                [self.aLevelPicker loadDataWith:^{
                    if (weakSelf.aUnitPicker.arrData.count <= 0) {
                        [MBProgressHUD showSuccess:@"当前没有可打卡课时" toView:self.view];
                        return;
                    }
                    [weakSelf.aUnitPicker show];
                }];

                
            }else {
                //TODO: 请选择级别 再选择单元
                
            }
            
        }
    }
}

-(void)gotoPictionCenter:(NSInteger)index{
    UIAlertController * alerVC = [UIAlertController alertControllerWithTitle:nil message:nil preferredStyle:UIAlertControllerStyleActionSheet];
    UIAlertAction * acOne = [UIAlertAction actionWithTitle:@"相册" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        //点击相册
        if ([self isPhotoAvailable]) {
            if ([UIImagePickerController isSourceTypeAvailable:UIImagePickerControllerSourceTypePhotoLibrary]) {
                _seleceIndexRow = index;
                self.isShowAdd = YES;
                UIImagePickerController *picker = [[UIImagePickerController alloc] init];
                picker.sourceType    = UIImagePickerControllerSourceTypePhotoLibrary;
                picker.delegate      = self;
                picker.allowsEditing = YES;
                
                [self presentViewController:picker animated:YES completion:^{
                }];
            }
        }
    }];
    //点击视频
    UIAlertAction * otherAc = [UIAlertAction actionWithTitle:@"视频" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        if ([UIImagePickerController isSourceTypeAvailable:UIImagePickerControllerSourceTypeSavedPhotosAlbum]) {
            _seleceIndexRow = index;
            self.isShowAdd = NO;
            UIImagePickerController *picker = [[UIImagePickerController alloc] init];
            picker.sourceType    = UIImagePickerControllerSourceTypePhotoLibrary;
            picker.delegate      = self;
            picker.allowsEditing = YES;
            picker.mediaTypes = @[(NSString *)kUTTypeMovie];
            picker.videoQuality = UIImagePickerControllerQualityTypeHigh;
            [self presentViewController:picker animated:YES completion:^{
            }];
        }
        
    }];
    //点击备课
    UIAlertAction * prepareLessonsAc = [UIAlertAction actionWithTitle:@"备课" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        HXCPrepareLessonsViewController *vc = [HXCPrepareLessonsViewController new];
        vc.block = ^(UIImage * _Nonnull image, NSString * _Nonnull url) {
            self.isVideo = NO;
            self.isImage = YES;
            self.isShowAdd = YES;
            NSMutableDictionary * tdic = self.rowMuarray[self.selectedIndex];
            [tdic setObject:@"2" forKey:@"fileType"];
            [tdic setObject:image forKey:@"image"];
            [tdic setObject:url forKey:@"videoCover"];
            [self.rowMuarray replaceObjectAtIndex:self.selectedIndex withObject:tdic];
            [self updateUIAndData];
//            self.isbeike = YES;
        };
        vc.hourId = self.hourId;
        [self presentViewController:vc animated:YES completion:nil];
    }];
    [alerVC addAction:acOne];
    if (!self.isImage) {
        [alerVC addAction:otherAc];
    }
    [alerVC addAction:prepareLessonsAc];
    UIAlertAction * cancerAc = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:^(UIAlertAction * _Nonnull action) {
        
    }];
    [alerVC addAction:cancerAc];
    [self presentViewController:alerVC animated:YES completion:^{
        
    }];
}
-(UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section {
    UIView *view = [[UIView alloc] initWithFrame:CGRectMake(0, 0, ScreenW, 11)];
    view.backgroundColor = [UIColor colorWithRed:242/255.0 green:242/255.0 blue:242/255.0 alpha:1];
    return view;
}
-(CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section {
    return 11.0;
}
-(UIView *)tableView:(UITableView *)tableView viewForFooterInSection:(NSInteger)section {
    return [UIView new];
}
-(CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section {
    return 0.01;
}
- (BOOL)isPhotoAvailable{
    ALAuthorizationStatus status = [ALAssetsLibrary authorizationStatus];
    if (status == ALAuthorizationStatusRestricted || status == ALAuthorizationStatusDenied){
        dispatch_async(dispatch_get_main_queue(), ^{
            UIAlertView *alertV = [[UIAlertView alloc] initWithTitle:@"温馨提示"
                                                             message:@"此应用没有权限访问您的照片或视频，您可以在“隐私设置”中启用访问"
                                                            delegate:nil
                                                   cancelButtonTitle:@"知道了"
                                                   otherButtonTitles:nil, nil];
            [alertV show];
        });
        return NO;
    }else{
        return YES;
    }
}

#pragma mark - UIImagePickerControllerDelegate
- (void)imagePickerController:(UIImagePickerController *)picker
didFinishPickingMediaWithInfo:(NSDictionary<NSString *,id> *)info{
    __block NSMutableDictionary * tdic = self.rowMuarray[self.selectedIndex];
    __weak typeof(self) weakSelf = self;
    [self dismissViewControllerAnimated:YES completion:^{
        __block UIImage *choseImage;
        self.isVideo = NO;
        self.isImage = YES;
        NSString * mediaType = [info objectForKey:UIImagePickerControllerMediaType];
        if ([mediaType isEqualToString:(NSString *)kUTTypeImage]) {
            
            choseImage = info[UIImagePickerControllerEditedImage];
            [tdic setObject:@"2" forKey:@"fileType"];
            [tdic setObject:choseImage forKey:@"image"];
            [self.rowMuarray replaceObjectAtIndex:self.selectedIndex withObject:tdic];
            
        }else if ([mediaType isEqualToString:(NSString *)kUTTypeMovie]){
            [tdic setObject:@"1" forKey:@"fileType"];
            self.isVideo = YES;
            self.isImage = NO;
            NSURL * video = (NSURL *)[info objectForKey:UIImagePickerControllerMediaURL];
            NSString * moviePath = [video path];
//            self.picker = nil;
            MPMoviePlayerController *player = [[MPMoviePlayerController alloc]initWithContentURL:video];
            //默认这个属性是yes 是否自动播放
            player.shouldAutoplay = NO;
            choseImage = [player thumbnailImageAtTime:1.0 timeOption:MPMovieTimeOptionNearestKeyFrame];
            [tdic setObject:choseImage forKey:@"image"];
            player = nil;
//            player.contentURL = nil;
            [self.rowMuarray replaceObjectAtIndex:self.selectedIndex withObject:tdic];
            
//            player.contentURL = nil;
            UploadModel *model = [UploadModel new];
            model.lastPathComponent = [video lastPathComponent];
            model.progressBlock = ^(CGFloat uploadPersent, NSString * _Nonnull progressLableText) {
                dispatch_async(dispatch_get_main_queue(), ^{
                    
                    Section3TableViewCell *cell = [self.tableView cellForRowAtIndexPath:[NSIndexPath indexPathForRow:self.selectedIndex inSection:2]];
                    cell.progressView.hidden = NO;
                    cell.progressView.progress = uploadPersent;
                });
            };
            self.aManager.successBlock = ^(NSString * _Nonnull fileStorePath) {
                
                [tdic setObject:fileStorePath forKey:@"videoPath"];
                [weakSelf.rowMuarray replaceObjectAtIndex:weakSelf.selectedIndex withObject:tdic];
                
            };
            [self.aManager uploadData:[NSData dataWithContentsOfFile:moviePath] withModel:model];
            //标记选择了视频
            
            __weak typeof(self)weakself = self;
            self.aManager.successBlock = ^(NSString * _Nonnull fileStorePath) {
//                NSLog(@"%@",fileStorePath);
                //                self.fileStorePath = fileStorePath;
                [weakSelf.filePathArry addObject:fileStorePath];
            };
//            NSLog(@"%@",self.filePathArry);
        }
        [self updateImage:choseImage];
        [self updateUIAndData];
        
    }];
}

-(void)updateUIAndData{
    [self.tableView reloadData];
}
#pragma mark - Cell Delegate
-(void)deleteCell:(Section3TableViewCell *)cell {
    NSLog(@"vc delete cell");
    NSInteger index = [self.tableView indexPathForCell:cell].row;
    if (index == 0) {
        //        cell.addButton.hidden = YES;
        return;
    }
    //
    [self.rowMuarray removeObjectAtIndex:index];
    if (self.rowMuarray.count==1) {
        self.isShowAdd = NO;
    }
//    NSLog(@"%lu",(unsigned long)self.rowMuarray.count);
    //i如果个数 1  isshowadd  = no
    [self.tableView reloadData];
}
-(void)addtionCell:(Section3TableViewCell *)cell {
    
//    NSLog(@"vc add cell");
    if (self.isVideo) {
        return;
    }
    //    NSInteger index = [self.tableView indexPathForCell:cell].row;
    
    NSMutableDictionary *tDic = [NSMutableDictionary dictionary];
    [self.rowMuarray addObject:tDic];
    [self.tableView reloadData];
}
-(void)deleteImage:(Section3TableViewCell *)cell {
//    NSLog(@"vc delete image");
    
    self.isVideo = NO;//删除视频后标记为NO
    //一种情况 删除视频
    if (self.isVideo) {
        [self.filePathArry removeAllObjects];
    }else{
        
    }
    
    NSInteger index = [self.tableView indexPathForCell:cell].row;
    //图片 并且是第一张图片
    if (index == 0 && self.rowMuarray.count == 1) {
        self.isImage = NO;
    }
    self.selectedIndex = index;
    NSMutableDictionary *dic = self.rowMuarray[index];
    dic[@"videoCover"] = nil;
    [self.rowMuarray replaceObjectAtIndex:index withObject:dic];
    [self.tableView reloadData];
}
-(void)addtionImage:(Section3TableViewCell *)cell {
//    NSLog(@"vc add image");
    NSInteger index = [self.tableView indexPathForCell:cell].row;
    self.selectedIndex = index;
    [self gotoPictionCenter:index];
}
-(void)changeInfo:(Section3TableViewCell *)cell {
    NSInteger index = [self.tableView indexPathForCell:cell].row;
    NSMutableDictionary *dic = self.rowMuarray[index];
    dic[@"infoContent"] = cell.textView.text;
    [self.rowMuarray replaceObjectAtIndex:index withObject:dic];
}
#pragma mark - actions  提交打卡内容
-(void)submitAction {
//    NSLog(@"submit...");
    //    [self.data setObject:@"2" forKey:@"clockType"];
    //    [self.data setObject:self.hourId forKey:@"hourId"];
    //    [self.data setObject:@"2" forKey:@"clockDate"];
    NSString *hourId = [NSString stringWithFormat:@"%@",self.hourId];
    NSString *courseId =[NSString stringWithFormat:@"%@",self.courseId];
    
    if (courseId.length==0||self.courseId==nil) {
        [MBProgressHUD showSuccess:@"请选择级别" toView:self.view];
        return;
    }
    if (hourId.length==0||self.hourId==nil) {
        [MBProgressHUD showSuccess:@"请选择单元" toView:self.view];
        return;
    }
    NSMutableDictionary *data = [NSMutableDictionary dictionary];
    NSString *token = [UserModel getUserModel].token;
    [data setObject:token forKey:@"token"];
    NSString *fileType;
    if (self.isVideo) {
        fileType = @"1";
        
    }else{
        fileType = @"2";
    }
    [data setObject:fileType forKey:@"fileType"];//文件类型 1 视频 2 图片
    [data setObject:courseId forKey:@"courseId"];
    [data setObject:hourId forKey:@"hourId"];
    [data setObject:self.clockType forKey:@"clockType"];//打卡状态 1 请假 2 打卡 3 补
    [data setObject:self.clockDate forKey:@"clockDate"];// 2019-03-09
    NSString *addToSociety;
    if (self.addToSociety) {
        addToSociety = @"1";
    }else{
        addToSociety = @"0";
    }
    [data setObject:addToSociety forKey:@"addToSociety"];// 2019-03-09
    if (self.isVideo) {
        if (self.filePathArry.count==0) {
            [MBProgressHUD showSuccess:@"正在上传视频" toView:self.view];
            return;
        }
    }else{
        
    }
    
    //如果是视频   封面链接   视频链接  内容
    //图片                 图片连接  内容
    NSMutableArray *videoTempArr = [NSMutableArray array];
    
    //    NSMutableArray *imageTempaArr = [NSMutableArray array];/
    if (self.isVideo) {
        for (int i=0; i<self.rowMuarray.count; i++) {
            NSDictionary *dic = self.rowMuarray[i];
            NSString *videoCover = dic[@"videoCover"];
            //            NSString *infoContent = dic[@"infoContent"];
            [videoTempArr addObject:videoCover];
            //            [self.contentArray addObject:infoContent];
            if (dic[@"infoContent"]==nil) {
                [self.contentArray addObject:@""];
            }else{
                NSString *infoContent = dic[@"infoContent"];
                [self.contentArray addObject:infoContent];
            }
        }
        [data setObject:videoTempArr[0] forKey:@"videoCover"];//视频封面
    }else{
        for (int i=0; i<self.rowMuarray.count; i++) {
            NSDictionary *dic = self.rowMuarray[i];
            NSString *videoCover = dic[@"videoCover"];
            //
            if (videoCover==nil) {
                [MBProgressHUD showSuccess:@"请选择视频或图片" toView:self.view];
                return;
            }
            //            NSString *infoContent = dic[@"infoContent"];
            [self.filePathArry addObject:videoCover];
            //            [self.contentArray addObject:infoContent];
            if (dic[@"infoContent"]==nil) {
                [self.contentArray addObject:@""];
            }else{
                NSString *infoContent = dic[@"infoContent"];
                [self.contentArray addObject:infoContent];
            }
        }
    }
    NSString *jsonString = [self contentJsonStringArray:self.contentArray];//视频内容
    NSString *jsonfilePathString = [self filePathJsonStringArray:self.filePathArry];//视频路径
    
    __weak typeof(self)weakSelf = self;
    
    [data setObject:jsonfilePathString forKey:@"filePaths"];
    [data setObject:jsonString forKey:@"contents"];
    
    [WYHXNetWorkManager post:WKCommitDakaContent_WKURL params:data completionHandler:^(id responseObj, NSError *error) {
        NSString *code = responseObj[@"code"];
        if ([code integerValue]==200) {
//            NSLog(@"%@",responseObj);
            [self.navigationController popViewControllerAnimated:YES];
            //提交用户选择记录（课程、课时）
            [weakSelf commitRecord:token courseId:courseId hourId:hourId];
        }
    }];
    
    //提交用户上一次选择的课程课时
}
#pragma mark - 描述视频路径或者图片路径换成json
- (NSString *)filePathJsonStringArray:(NSMutableArray *)array{
    NSError *fileError = nil;
    NSData *filepathjsonData = [NSJSONSerialization dataWithJSONObject:array
                                                               options:kNilOptions
                                                                 error:&fileError];
    
    NSString *jsonfilePathString = [[NSString alloc] initWithData:filepathjsonData
                                                         encoding:NSUTF8StringEncoding];
    return jsonfilePathString;
}
#pragma mark - 描述内容转换成json
- (NSString *)contentJsonStringArray:(NSMutableArray *)array{
    //内容路径
    NSError *error = nil;
    NSData *jsonData = [NSJSONSerialization dataWithJSONObject:array
                                                       options:kNilOptions
                                                         error:&error];
    
    NSString *jsonString = [[NSString alloc] initWithData:jsonData
                                                 encoding:NSUTF8StringEncoding];
    return jsonString;
}
- (void)commitRecord:(NSString *)token courseId:(NSString *)courseId hourId:(NSString *)hourId{
    NSMutableDictionary *data = [NSMutableDictionary dictionary];
    [data setObject:courseId forKey:@"courseId"];
    [data setObject:token forKey:@"token"];
    [data setObject:hourId forKey:@"hourId"];
    [WYHXNetWorkManager post:WKQueryinsertLastSelectCourseHourr_WKURL params:data completionHandler:^(id responseObj, NSError *error) {
        NSString *code = responseObj[@"code"];
        if ([code integerValue]==200) {
//            NSLog(@"%@",responseObj);
//            NSLog(@"提交结果成功");
        }
    }];
}
- (void)optionAction:(UIButton *)sender{
//    NSLog(@"option...");
    sender.selected = !sender.selected;
    
    if (sender.selected) {
        self.addToSociety = YES;
    }else{
        self.addToSociety = NO;
    }
}
- (void)updateImage:(UIImage *)image {
    NSData *data = UIImageJPEGRepresentation(image, 0.7);
    //@"http://47.95.9.40/vlearn/ClockController/clockUploadImage"
    NSString *token = [UserModel getUserModel].token;
    [WYHXNetWorkManager uploadSinglePhotoWith:WKUploadImage_WKURL params:@{@"token":token} WithDataArray:@[data].copy withParamsArray:@[@"file"].copy AndFinish:^(NSDictionary *res, NSError *err) {
        NSMutableDictionary *dic = self.rowMuarray[self.selectedIndex];
        [dic setObject:res[@"data"] forKey:@"videoCover"];
        [self.rowMuarray replaceObjectAtIndex:self.selectedIndex withObject:dic];
        
    }];
    
}


#pragma mark - views
-(UnitPicker *)aUnitPicker {
    if (!_aUnitPicker) {
        _aUnitPicker = [UnitPicker new];
        _aUnitPicker.delegate = self;
    }
    return _aUnitPicker;
}
-(LevelPicker *)aLevelPicker {
    if (!_aLevelPicker) {
        _aLevelPicker = [LevelPicker new];
        _aLevelPicker.delegate = self;
    }
    return _aLevelPicker;
}

-(void)clickOK:(id)selectData pickerView:(BasePickerView *)pickerView {
    if (pickerView == self.aUnitPicker) {
        [self.data setObject:selectData forKey:@"unit"];

//        [self.data setObject:@{} forKey:@"level"];
    }else {
        [self.data setObject:selectData forKey:@"level"];
        [self.data setObject:@{} forKey:@"unit"];
    }
    [self.tableView reloadData];
}
- (void)loadLevelData {
    
    NSMutableDictionary *data = [NSMutableDictionary dictionary];
    
    [data setObject:[UserModel getUserModel].token forKey:@"token"];
    
    [WYHXNetWorkManager get:WKSelectLastSelectCourseHour_WKURL params:data completionHandler:^(id responseObj, NSError *error) {
        
        if ([responseObj[@"code"] integerValue] == 200) {
            NSArray *tArr =  responseObj[@"data"];
            for (NSDictionary *dic in tArr) {
                if ([dic[@"isSelect"] boolValue]) {
                    [self.data setObject:dic forKey:@"level"];
                    NSArray *arr2 = dic[@"clockCourseHourVOList"];
                    self.dataArray = arr2;
                    if (![arr2 isKindOfClass:[NSArray class]]) {
                        continue;
                    }
                    for (NSDictionary *dic2 in arr2) {
                        if (dic[@"isSelect"]) {
                            [self.data setObject:dic2 forKey:@"unit"];
                        }
                        break;
                    }
                    break;
                }
            }
            self.levelArr = responseObj[@"data"];
            [self.tableView reloadData];
        }
    }];
}
@end
